/*
 * Copyright 2007 Brian Watkins
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */


package bw.cal;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.text.*;
import bw.util.*;
import bw.note.*;

public class CalServlet extends HttpServlet
{
    public static final String CALENDAR = "bw_calendar";
    public static final String PREVIOUS_MONTH = "previous";
    public static final String NEXT_MONTH = "next";
    public static final String CURRENT_MONTH = "current";
    public static final String THIS_MONTH = "thisMonth";

    private SimpleDateFormat _format = new SimpleDateFormat( "MMMM yyyy" );
    private SimpleDateFormat _dayFormat = new SimpleDateFormat( "d" );

    public void doGet ( HttpServletRequest req, HttpServletResponse res ) 
        throws ServletException, IOException
    {
        String action = req.getParameter( "action" );
        String numStr = req.getParameter( "number" );

        int number = 0;
        try
        {
            number = Integer.parseInt( numStr );
        }
        catch ( NumberFormatException ex )
        {
            System.out.println( "CalServlet: Bad Number string! (" + numStr + ")" );
            number = 2;
        }

        GregorianCalendar cur = DateFactory.getInstance().getCalendar();

        HttpSession session = req.getSession();
        GregorianCalendar cal = (GregorianCalendar) session.getAttribute( CalServlet.CALENDAR );
        if ( cal == null )
        {
            cal = DateFactory.getInstance().getCalendar();
            session.setAttribute( CalServlet.CALENDAR, cal );
        }

        if ( PREVIOUS_MONTH.equals( action ) )
        {
            cal.add( Calendar.MONTH, -1 );
        }
        else if ( NEXT_MONTH.equals( action ) )
        {
            cal.add( Calendar.MONTH, 1 );
        }
        else if ( THIS_MONTH.equals( action ) )
        {
            cal.setTime( DateFactory.getInstance().getDate() );
        }

        res.setContentType( "text/xml" );

        PrintWriter out = res.getWriter();

        out.println( "<calendars>" );

        for ( int i = 0; i < number; i++ )
        {
            String title = _format.format( cal.getTime() );
            int length = cal.getActualMaximum( Calendar.DAY_OF_MONTH );
            cal.set( Calendar.DAY_OF_MONTH, 1 );
            int start = cal.get( Calendar.DAY_OF_WEEK ) - 1;
            int month = cal.get( Calendar.MONTH );
            int year = cal.get( Calendar.YEAR );

            int current = -1; 
            if ( cur.get( Calendar.MONTH ) == cal.get( Calendar.MONTH ) &&
                 cur.get( Calendar.YEAR ) == cal.get( Calendar.YEAR ) )
            {
                current = cur.get( Calendar.DAY_OF_MONTH );
            }

            out.print( "<calendar title=\"" + title + 
                       "\" month=\"" + month +
                       "\" year=\"" + year + 
                       "\" length=\"" + length + 
                       "\" start=\"" + start + 
                       "\" current=\"" + current + "\"" );

            Vector events = getEventsForCal( cal );
            
            if ( events.size() > 0 )
            {
                out.println( ">" );
            }

            for ( Enumeration e = events.elements(); e.hasMoreElements(); )
            {
                CalendarEvent evt = (CalendarEvent) e.nextElement();
                out.println( "<event date=\"" + _dayFormat.format( evt.getTime().getStart() ) + 
                             "\" desc=\"" + Util.XMLEscape( evt.getDescription() ) + "\" />" );
            }

            if ( events.size() > 0 )
            {
                out.println( "</calendar>" );
            }
            else
            {
                out.println( " />" );
            }

            cal.add( Calendar.MONTH, 1 );
        }

        //roll the calendar back to the beginning
        cal.add( Calendar.MONTH, ( 0 - number ) );

        out.println( "</calendars>" );
        out.close();
    }

    private Vector getEventsForCal ( GregorianCalendar cal )
    {
        CalendarEventManager manager = CalendarEventManager.getInstance();

        return manager.getAlertableEventsForMonth( cal.getTime() );
    }
}